<template>
  <div class="account-container">
    <div class="title">个人信息</div>
    <div class="account-info" style="width: 500px;">
      <el-form :model="userInfoForm" ref="userInfoForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input :value="userInfoForm.username" placeholder="用户名" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input :value="userInfoForm.phone" placeholder="手机号" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input :value="userInfoForm.email" placeholder="邮箱" disabled></el-input>
        </el-form-item>

        <el-form-item label="登录密码">
          <el-input :value="userInfoForm.password" placeholder="登录密码" show-password>
            <el-button slot="append" @click="updatePassword">修改密码</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" v-if="isUpdatePassword" show-password>
          <el-input v-model="newPassword" placeholder="新密码" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" v-if="isUpdatePassword" show-password>
          <el-input v-model="checkPassword" placeholder="确认密码" autocomplete="off" show-password></el-input>
        </el-form-item>

        <el-form-item label="用户头像">
          <div v-if="!isUpdateAvatar" class="user-avatar" @click="updateAvatar">
            <img :src="userInfoForm.avatar" alt="" v-if="userInfoForm.avatar">
            <el-avatar icon="el-icon-user-solid" shape="square" :size="120" v-else></el-avatar>
          </div>
          <div class="upload-avatar" v-else>
            <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1"
                       :class="{'hide': hideUpload}" :on-change="handleUpload">
              <i slot="default" class="el-icon-plus"  v-if="!avatarUrl"></i>
              <div slot="file" v-else>
                <img class="el-upload-list__item-thumbnail" :src="avatarUrl" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button type="primary" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {baseUrl} from "../../api";

export default {
  name: "Account",
  data() {
    return {
      userInfo: {},

      userInfoForm: {
        // id: '1',
        // username: 'tianyu',
        // phone: '13574100502',
        // email: '27556030912@qq.com',
        // password: '123456',
        // avatar: '/static/avatar.png'
      },

      isUpdatePassword: false,
      newPassword: '',
      checkPassword: '',

      isUpdateAvatar: false,
      hideUpload: false,
      fileList: [],
      avatarUrl: ''
    }
  },
  methods: {
    getUserInfo() {
      let {userId, token}= this.userInfo;
      this.$http.get('/admin/getUserInfo/'+userId, {
        headers: { Authorization: token }
      }).then(response=>{
        let result= response.data;
        if(result.code===200) {
          this.userInfoForm= JSON.parse(result.data);
          this.userInfoForm.avatar= baseUrl + this.userInfoForm.avatar;
        } else {
          this.$message.error('获取用户信息失败！');
        }
      }).catch(e=>{
        this.$message.error('获取用户信息失败！');
      })
    },


    // 更新密码
    updatePassword() {
      this.$confirm('是否更新密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isUpdatePassword= true;
      }).catch(() => {});
    },

    // 更新头像
    updateAvatar() {
      this.$confirm('是否更新头像?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isUpdateAvatar= true;
      }).catch(() => {});
    },
    // 头像上传，注意：此时并未上传至服务端
    handleUpload(file, fileList) {
      // console.log(file, fileList);
      this.fileList= fileList;

      // 预览上传的图片
      let URL= window.URL || window.webkitURL;
      this.avatarUrl = URL.createObjectURL(file.raw);
      this.hideUpload= true;
    },
    // 删除最新上传的头像
    handleRemove() {
      this.fileList.pop();
      this.avatarUrl= '';
      this.hideUpload= false;
    },

    // 提交
    submit() {
      if(!this.isUpdatePassword && !this.isUpdateAvatar) return;
      // 更新了密码
      if(this.isUpdatePassword) {
        if(!this.newPassword) {
          this.$message.error('请输入新密码！！！');
          return ;
        }
        if(!this.newPassword) {
          this.$message.error('请输入确认密码！！！');
          return ;
        }
        if(this.newPassword !== this.checkPassword) {
          this.$message.error('更新密码时，新密码与确认密码输入不一致！！！');
          return ;
        }
      }
      // 更新了头像
      if(this.isUpdateAvatar) {
        if(!this.fileList.length) {
          this.$message.error('头像更新失败！！！');
          return ;
        }
      }
      let self= this;
      let formData = new FormData();  // 首先创建FormData对象
      formData.append('id', this.userInfoForm.id);
      if(this.fileList.length) {
        formData.append('file', this.fileList[0].raw);
      }
      if(this.newPassword) {
        formData.append('password', this.newPassword);
      }
      let token= this.userInfo.token;
      this.$http({
        url: '/admin/updateAccountInfo',
        method: 'post',
        headers:{ Authorization: token },
        data: formData
      }).then(response=>{
        let res= response.data;
        if(res.code===200) {
          this.userInfoForm= JSON.parse(res.data);
          this.userInfoForm.avatar= baseUrl + this.userInfoForm.avatar;
          self.$message.success('更新用户信息成功！！！');
          self.cancel();
        } else {
          self.$message.warning('更新用户信息失败！！！');
        }
      }).catch(e=>{
        self.$message.warning('更新用户信息失败！！！');
      });
    },
    // 取消更新
    cancel() {
      this.isUpdateAvatar= false;
      this.isUpdatePassword= false;
      this.hideUpload= false;
      this.fileList= [];
      this.avatarUrl= '';
      this.newPassword= '';
      this.checkPassword= '';
    }
  },
  mounted() {
    let userInfo= window.sessionStorage.getItem('userInfo');
    this.userInfo= JSON.parse(userInfo);
    this.getUserInfo();
  }
}
</script>

<style scoped lang="less">
  .account-container {
    .title {
      box-sizing: border-box;
      width: 100%;
      height: 50px;
      line-height: 40px;
      padding: 5px 10px;
      font-size: 24px;
      color: #fff;
      border-radius: 4px;
      background: #007BFF;
      margin-bottom: 20px;
    }

    .user-avatar {
      width: 120px;
      height: 120px;
      cursor: pointer;
      img {
        border-radius: 4px;
        width: 100%;
        height: 100%;
      }
    }

    .upload-avatar {
      height: 120px;
      //line-height: 120px;
      & > div {
        height: 100%;
      }

      .hide /deep/ .el-upload--picture-card {
        display: none;
      }

      /deep/ .el-upload, /deep/ .el-upload--picture-card {
        width: 120px;
        height: 120px;
        line-height: 120px;
      }
      .el-upload-list--picture-card {
        width: 120px;
        height: 120px;
        line-height: 120px;
      }
      .el-upload-list--picture-card .el-upload-list__item-thumbnail,
      /deep/ .el-upload-list--picture-card .el-upload-list__item,
      /deep/ .el-upload-list--picture-card .el-upload-list__item-actions {
        width: 120px;
        height: 120px;
        line-height: 120px;
      }
    }
  }
</style>
